package org.bjf.aop;

import lombok.extern.slf4j.Slf4j;
import org.bjf.exception.CommMsgCode;
import org.bjf.exception.ServiceException;
import org.bjf.utils.ExceptionAssert;
import org.bjf.utils.SignUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 签名校验拦截器
 *
 * @author binjinfeng
 */
@Component
@Slf4j
public class SignInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        validSign(parameterMap);

        return Boolean.TRUE;
    }

    private void validSign(Map<String, String[]> parameterMap) {
        String[] arr = parameterMap.get("sign");
        ExceptionAssert.notEmpty(arr, CommMsgCode.INVALID_SIGN);
        String sign = arr[0];

        //===1.取出签名字段
        Map<String, String> signMap = new HashMap<>();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            if (entry.getValue().length > 1) {
                //　数组不参与签名
                continue;
            }
            signMap.put(entry.getKey(), entry.getValue()[0]);
        }

        //===2.验证签名
        String mySign = SignUtil.sign(signMap);
        if (!mySign.equals(sign)) {
            throw new ServiceException(CommMsgCode.INVALID_SIGN);
        }
    }
}
